<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\service\Material as MaterialService;

class SkuMaterial extends Base
{

	/**
	 * 根据订单ID获取材料列表
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param integer $skuId
	 * @return array
	 */
	public function getListBySkuId($skuId, $materialType='') {
		if (empty($skuId)) return [];
		$list = db('sku_material')->where('sku_id', $skuId)->select();
		$materialService = new MaterialService();
		$n = 0;
		$result = [];
		foreach ($list as $k => $v) {
			$mInfo = $materialService->getInfoById($v['material_id']);
			if ($materialType== '' || $materialType == $mInfo['type']) {
				$result[$n] = $v;
				$result[$n]['mInfo'] = $mInfo;
				$n++;
			}
		}
		return $result;
	}

	/**
	 * 根据ID获取记录信息
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param integer $id
	 * @param string $field
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		$materialService = new MaterialService();
		$info = db('sku_material')->where('mid', $id)->field($field)->findOrEmpty();
		if ($info && isset($info['material_id'])) {
			$info['mInfo'] = $materialService->getInfoById($info['material_id']);
		}
		return $info;
	}

	/**
	 * 根据SKU和物料ID获取行记录
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param string $sku
	 * @param integer $materialId
	 * @param string $field
	 * @return array|PDOStatement|string|\think\Model
	 */
	public function getInfoByMaterialId($sku, $materialId, $field='*') {
		if (empty($sku) || empty($materialId)) return [];
		$info = db('sku_material')->where('sku_id', db('sku')->where('sku', $sku)->value('id', 0))->where('material_id', $materialId)->field($field)->findOrEmpty();
		$materialService = new MaterialService();
		if ($info && isset($info['material_id'])) {
			$info['mInfo'] = $materialService->getInfoById($info['material_id']);
		}
		return $info;
	}
}